package com.ttpai.boot.lbs.service.ok;

import com.ttpai.boot.lbs.dao.MetroPointDAO;
import com.ttpai.boot.lbs.model.MetroPointVO;
import com.ttpai.boot.lbs.util.LLUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by kail on 2017/3/11.
 */
@Service
public class MetroPointService {

    @Autowired
    private MetroPointDAO metroPointDAO;

    @Autowired
    private MetroPointTimeService pointTimeService;

    private static final Map<String, Map<String, MetroPointVO>> cache = new HashMap<>();

    /**
     * 查询一个城市内的所有地铁
     * // FIXME 地铁坐标信息存入 Redis GeoHash
     */
    public Map<String, MetroPointVO> selectAllMetroByCity(String cityName) {
        Map<String, MetroPointVO> returnData = cache.get(cityName);
        if (null == returnData) {
            MetroPointVO select = new MetroPointVO();
            select.setCityName(cityName + "%");

            returnData = new HashMap<>();
            List<MetroPointVO> metroPointVOS = metroPointDAO.selectAllMetroPoint(select);
            for (MetroPointVO metro : metroPointVOS) {
                returnData.put(metro.getName(), metro);
            }
            cache.put(cityName, returnData);
        }
        return returnData;
    }


    /**
     * 查找距离最近的地铁点
     * // FIXME 通过 Redis GeoHash 获得
     */
    public MetroPointVO selectNearMetro(String cityName, Double lng, Double lat) {
        Map<String, MetroPointVO> metroPoints = selectAllMetroByCity(cityName);
        double minDistance = Double.MAX_VALUE;
        MetroPointVO minDistancePoint = null;
        for (Map.Entry<String, MetroPointVO> metroPoint : metroPoints.entrySet()) {
            double linearDistance = LLUtil.getLinearDistance(metroPoint.getValue().getLng(), metroPoint.getValue().getLat(), lng, lat);
            if (linearDistance < minDistance) {
                minDistance = linearDistance;
                minDistancePoint = metroPoint.getValue();
            }
        }
        return minDistancePoint;
    }

    /**
     * 通过站点名获取经纬度
     */
    public MetroPointVO selectNearMetro(String cityName, String metroName) {
        return selectAllMetroByCity(cityName).get(metroName);
    }

    /**
     * 通过站点名获取经纬度
     */
    public List<MetroPointVO> selectNearMetro(String cityName, List<String> metroName) {
        List<MetroPointVO> returnList = new ArrayList<>();
        for (String name : metroName) {
            returnList.add(selectAllMetroByCity(cityName).get(name));
        }
        return returnList;
    }

}
